package com.example.demo.demos.example;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author lyh
 * @date 2025/5/7 9:33
 */
public class ReflectTest {
    public static void main(String[] args) {
        try {
            // 通过类名动态创建对象
            Class<?> clazz = Class.forName("com.example.demo.demos.pojo.Student");

            Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
            Object obj = constructor.newInstance("Alice", 20);

            System.out.println(obj);

            // 调用方法
            Method method = clazz.getMethod("study", String.class);
            method.invoke(obj, "study reflect");

            // 访问私有字段
            Field fieldName = clazz.getDeclaredField("name");
            fieldName.setAccessible(true);
            fieldName.set(obj, "Reflect");

            System.out.println(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
